// pages/publish/publish.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    Date:null,
    index:0,
    index2:0,
    picker: ['公告', '教学', '交流'],
    stupicker:['教学','交流'],
    classpicker:[],
    imgList: [],
    images_success:[],
    images_success2:[],
    images_success_size:0,
    isStu: false,
    isTea: false,
    ievent: null,
  },

  PickerChange(e) {
    console.log(e);
    this.setData({
      index: e.detail.value
    })
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //console.log(this.data.Date)
    let userInfo = wx.getStorageSync('userInfo');
    if(userInfo.status == 'teacher'){
      this.setData({
        isTea: true,
      })
    }
    else{
      this.setData({
        isStu: true,
      })
    }
    for(let item of userInfo.classinfo){
      item.fName= item.className+item.lessonName
    }
    this.setData({
      classpicker: userInfo.classinfo,
    })
    console.log(this.data.classpicker)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
          if (typeof this.getTabBar === 'function' &&
            this.getTabBar()) {
            this.getTabBar().setData({
              selected: 1
            })
        }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  ChooseImage() {
    wx.chooseImage({
      count: 4, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album'], //从相册选择
      success: (res) => {
        if (this.data.imgList.length != 0) {
          this.setData({
            imgList: this.data.imgList.concat(res.tempFilePaths)
          })
        } else {
          this.setData({
            imgList: res.tempFilePaths
          })
        }
      }
    });
    
  },
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  DelImg(e) {
    wx.showModal({
      title: 'hallo',
      content: '确定要删除这张图片吗？',
      cancelText: '再看看',
      confirmText: '删除',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },
  sumbit(e){
    let userInfo = wx.getStorageSync('userInfo')
    let that = this
    let _class = null
    if(this.data.isTea){
      _class = that.data.picker[that.data.index] 
    }
    else{
     _class = that.data.stupicker[that.data.index] 
    }
    let _lesson = that.data.classpicker[that.data.index2]
    let _date = new Date()
    this.setData({
      ievent : e
    })
    wx.showLoading({
      title: '发表中',
    })
    if(this.data.imgList.length > 0){
      this.uploadImage(0 , e)
    }
    else{
      var {title, content} = e.detail.value;
        const db = wx.cloud.database();
          db.collection('messageInfo').add({
            data: {
              title:title,
              info: content,
              date: _date,
              class: _class,
              pname: userInfo.nickName,
              avatarUrl: userInfo.avatarUrl,
              likeNum:0,
              replyNum:0,
              seeNum:0,
              imgList: that.data.images_success2,
              status: userInfo.status,
              cId: _lesson.cid
            }
            })
            .then(res => {
              wx.hideLoading()
              wx.showToast({
                icon: 'none',
                title: '提交成功',
              })
              wx.reLaunch({
                url: '../index/index',
              })
            })
            .catch(err => {
              wx.hideLoading()
              wx.showToast({
                icon: 'none',
                title: '提交失败',
              })
            })
    }
},

addImagePath(fileId) {
  let userInfo = wx.getStorageSync('userInfo')
  let that = this
  let _class = null
  if(this.data.isTea){
    _class = that.data.picker[that.data.index] 
  }
  else{
   _class = that.data.stupicker[that.data.index] 
  }
  let _lesson = that.data.classpicker[that.data.index2]
  let _date = new Date()
  wx.cloud.getTempFileURL({
    fileList: [fileId],
    success: res => {
      that.data.images_success2.push(res.fileList[0].tempFileURL);
      that.data.images_success_size = that.data.images_success_size + 1;
      if(that.data.images_success_size == that.data.imgList.length){
        var {title, content} = that.data.ievent.detail.value;
        const db = wx.cloud.database();
          db.collection('messageInfo').add({
            data: {
              title:title,
              info: content,
              date: _date,
              class: _class,
              pname: userInfo.nickName,
              avatarUrl: userInfo.avatarUrl,
              likeNum:0,
              replyNum:0,
              seeNum:0,
              imgList: that.data.images_success2,
              status: userInfo.status,
              cId: _lesson.cid
            }
            })
            .then(res => {
              wx.hideLoading()
              wx.showToast({
                icon: 'none',
                title: '提交成功',
              })
              wx.reLaunch({
                url: '../index/index',
              })
            })
            .catch(err => {
              wx.hideLoading()
              wx.showToast({
                icon: 'none',
                title: '提交失败',
              })
            })
            console.log(this.data.images_success)
      }
      console.log("获取url地址：",res.fileList[0].tempFileURL);
    },
    fail: console.error
  })
},

  uploadImage(index ){
    console.log(this.data.ievent)
    let userInfo = wx.getStorageSync('userInfo')
    let that = this
    let cloudpath = 'images/' + new Date().getTime() + "_" + userInfo.nickName +"_"+ Math.floor(Math.random()*10000) + ".jpg" //使用时间戳加随机数给图片命名
      wx.cloud.uploadFile({//上传至微信云存储
        cloudPath: cloudpath,
        filePath: that.data.imgList[index],// 本地文件路径
        success: res => {
          // 返回文件 ID
          //console.log("上传成功",res)
          that.data.images_success[index] = res.fileID;
          that.data.images_success_size = that.data.images_success_size + 1;
 
          if(that.data.images_success_size == that.data.imgList.length){
            that.data.images_success_size = 0,
            console.log("上传成功：", that.data.images_success)
            this.data.images_success.forEach((i) =>{
              this.addImagePath(i)
            })
            
          }else {
            that.uploadImage(index+1 )
          }
        },
        fail: err =>{
          console.log(err)
          that.setData({
            images_success:[],
            images_success_size:0
          })
          wx.showToast({
            icon:'none',
            title: '上传失败，请重新上传',
          })
        }
      })
 
  },
})